package com.jdkreader.concurrency.concurrent.simulation;


import java.util.concurrent.TimeUnit;

/**
 * 服务员
 */
public class Teller implements Runnable,Comparable<Teller>{

    private static int counter = 0;
    private final int id = counter++;
    private CustomerLine customers;
    //服务员已经服务的顾客数量
    private int customerServered=0;
    //服务员是否已经服务过当前顾客队列
    private boolean servingCustomerLine=true;

    public Teller(CustomerLine line){
        customers=line;
    }

    public void run(){
        try{
            while(!Thread.interrupted()){
                Customer customer=customers.take();
                //模拟服务员服务顾客
                TimeUnit.SECONDS.sleep(customer.getServerTime());
                synchronized(this){
                    customerServered++;
                    while(!servingCustomerLine){
                        wait();
                    }
                }
            }
        }catch(Exception e){
            System.out.println(this+" interrupted");
            e.printStackTrace();
        }
        System.out.println(this+" terminating");
    }

    public synchronized void doSomeThingElse(){
        customerServered=0;
        servingCustomerLine=false;
    }

    public synchronized void serverCustomerLine(){
        //断言为真才继续执行
        assert !servingCustomerLine:"already serving: "+this;
        servingCustomerLine=true;
        //唤醒休眠线程
        notifyAll();
    }

    public String toString(){
        return "Teller "+id+" ";
    }
    public String shortString(){
        return "T "+id+" ";
    }

    public synchronized int compareTo(Teller other){
        return customerServered < other.customerServered?-1:
                (customerServered == other.customerServered?0:1);
    }

}
